


import random
import numpy as np
import pandas as pd
from db_interface import db_interface
from public_func.exchange_date import cal_stock_exchange_date

def stock_price_change():
    start_date, end_date = cal_stock_exchange_date(days=30)
    sql = f"select code, name, date, `now` from stock_days_sh where date between '{start_date}' and '{end_date}' " \
          f"order by code, date desc"
    query = db_interface.stock_base.select(sql)
    stock_dict = {}
    for item in query:
        code, name, date, now = item
        date = date.strftime('%Y-%m-%d')
        # print(code, name, date, now)
        if code not in stock_dict:
            stock_dict[code] = []
        stock_dict[code].append((name, date, now))

    last_date = None
    f = open("./stock_break.txt", "w", encoding="utf-8")
    for k, v in stock_dict.items():
        print(k, )
        _last_date = v[0][1]
        if not last_date:
            last_date = _last_date
        last_price = v[0][2]
        avg_5 = sum([x[2] for x in v[:5]])/5
        avg_10 = sum([x[2] for x in v[:10]]) / 10
        avg_20 = sum([x[2] for x in v[:20]]) / 20
        diff1 = abs((last_price - avg_5)/last_price)  ## 1、最新价与5日均线
        diff2 = abs((last_price - avg_10) / last_price)  ## 2、最新价与10日均线
        diff3 = abs((last_price - avg_20) / last_price)  ## 3、最新价与20日均线
        diff4 = abs((avg_5 - avg_10) / avg_5)  ## 4、5日均线与10日均线
        diff5 = abs((avg_5 - avg_20) / avg_5)  ## 5、5日均线与20日均线
        diff6 = abs((avg_10 - avg_20) / avg_10)  ## 6、10日均线与20日均线
        diff_list = [diff1, diff2, diff3, diff4, diff5, diff6]
        diff_filter = [x <= 0.03 for x in diff_list]
        if len(diff_filter) >= 4:
            print("围绕及突破均线:", k, v, [diff1, diff2, diff3, diff4, diff5, diff6])
            f.write("%s:%s,%s,%s\n"%(v[0][0], k, str(diff_list), str(v)))





if __name__ == '__main__':
    stock_price_change()